package org.jeecg.modules.demo.api.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.net.URLDecoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.sun.management.OperatingSystemMXBean;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ZzSecurityHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.api.service.IApiInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.BaseColor;

import org.jeecg.modules.demo.dwxx.entity.SysDwxx;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.system.util.*;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: ap
 * @Author: jeecg-boot
 * @Date:   2023-10-27
 * @Version: V1.0
 */
@RestController
@RequestMapping("/ap/apInfo")
@Slf4j
public class ApiInfoController {
	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;
	 @Value(value = "${jeecg.path.thumbnail}")
	 private String thumbnail;
	 @Value(value = "${jeecg.domainUrl.Dpuburl}")
	 private String Dpuburl;
	 @Autowired
	 private IApiInfoService apiInfoService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 /**
	  * 常规11号
	  */
	 private static Font textFont;
	 /**
	  * 加黑11号
	  */
	 private static Font bodyBlockFont;


	 @ApiOperation(value="通过部门受案号查询2.0系统", notes="通过部门受案号查询2.0系统")
	 @GetMapping(value = "/E_QueryBMSAH")
	 public String QueryBMSAH(HttpServletRequest request, HttpServletResponse response) {
		 JSONObject res = apiInfoService.getall("");
		 String retStr = res.toJSONString();
		 return retStr;
	 }


	 @ApiOperation(value="查询目录模板", notes="查询目录模板")
	 @PostMapping(value = "/daml")
	 public String Querydaml(HttpServletRequest request, HttpServletResponse response) {
		 JSONObject res = apiInfoService.getdaml();
		 String retStr = res.toJSONString();
		 return retStr;
	 }

	 @ApiOperation(value="生成打印文件", notes="生成打印文件")
	 @PostMapping(value = "/print")
	 public String print(HttpServletRequest request, HttpServletResponse response) {

		 Document document = new Document(PageSize.A4);

		 String path =  "D:\\1.pdf";
		 try{

			 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
			 document.open();
			 document.newPage();
			 String fontPath="D:/SimHei.ttf";
			 BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

			 // 蓝色字体
			 Font blueFont = new Font(bfChinese);
			 blueFont.setColor(BaseColor.BLUE);
			 blueFont.setSize(5);

			 // 小三号
			 Font smallThreeFont = new Font(bfChinese, 15);
			 smallThreeFont.setColor(BaseColor.BLACK);

			 // 五号
			 Font fiveFont = new Font(bfChinese);
			 fiveFont.setColor(BaseColor.BLACK);
			 fiveFont.setSize(10.5f);

			 // 五号
			 Font smallFiveFont = new Font(bfChinese);
			 smallFiveFont.setColor(BaseColor.BLACK);
			 smallFiveFont.setSize(9);

			 // 五号
			 Font smallSixFont = new Font(bfChinese);
			 smallSixFont.setColor(BaseColor.BLACK);
			 smallSixFont.setSize(6.5f);

			 // 小四号 加粗
			 Font greenFont = new Font(bfChinese, 12, Font.BOLD);
			 greenFont.setColor(BaseColor.BLACK);

			 // 小四号
			 Font messFont = new Font(bfChinese, 12);
			 messFont.setColor(BaseColor.BLACK);


			 // 标题加粗 四号
			 Font titleFont = new Font(bfChinese, 14, Font.BOLD);
			 titleFont.setColor(BaseColor.BLACK);


			 // 设计一个4列的表.
			 PdfPTable table = new PdfPTable(4);
			 table.setWidthPercentage(100); // 宽度100%填充
			 table.setSpacingBefore(10f); // 前间距
			 table.setSpacingAfter(10f); // 后间距


			 // 设置列宽
			 float[] columnWidths = { 0.8f, 0.8f, 0.5f,0.5f};
			 table.setWidths(columnWidths);
			 PdfPCell cell;

			 //第一行
			 cell = new PdfPCell(new Phrase("", smallThreeFont));
			 cell.setMinimumHeight(20); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 table.addCell(cell);

			 cell = new PdfPCell(new Phrase("申请复印档案目录", smallThreeFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorderWidthTop(0);
			 cell.setBorderWidthLeft(0);
			 cell.setBorderWidthRight(0);
			 table.addCell(cell);

			 cell = new PdfPCell(new Phrase("", fiveFont));
			 cell.setMinimumHeight(2); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 table.addCell(cell);
			 //第二行

			 cell = new PdfPCell(new Phrase("", fiveFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 table.addCell(cell);


			 //第三行

			 cell = new PdfPCell(new Phrase("", fiveFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 table.addCell(cell);

			 cell = new PdfPCell(new Phrase("申请日期：XXXX年XX月XX日", fiveFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 table.addCell(cell);

			 cell = new PdfPCell(new Phrase("申请编号：XXXXX号", fiveFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 cell.setColspan(2);
			 table.addCell(cell);

			 PdfPTable pdfPTable = new PdfPTable(2);
			 pdfPTable.setWidthPercentage(100); // 宽度100%填充
			 cell = new PdfPCell(new Phrase("文件类型", fiveFont));
			 cell.setMinimumHeight(30); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中

			 pdfPTable.addCell(cell);
			 cell = new PdfPCell(new Phrase("文件名称", fiveFont));
			 cell.setMinimumHeight(30); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 pdfPTable.addCell(cell);
			 /**
			  * 加入到pdf文档中
			  */
			 cell = new PdfPCell(new Phrase("入伍材料", fiveFont));
			 cell.setMinimumHeight(30); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中

			 pdfPTable.addCell(cell);
			 cell = new PdfPCell(new Phrase("入伍材料文件", fiveFont));
			 cell.setMinimumHeight(30); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中

			 pdfPTable.addCell(cell);
			 /**
			  * 加入到pdf文档中
			  */

			 cell = new PdfPCell(new Phrase("", fiveFont));
			 cell.setMinimumHeight(40); // 设置单元格高度
			 cell.setUseAscender(true); // 设置可以居中
			 cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); // 设置水平居中
			 cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
			 cell.setBorder(0);
			 cell.setColspan(4);
			 cell.addElement(pdfPTable);
			 table.addCell(cell);
			 document.add(table);
			 // 表尾
			 Paragraph thrtionTitle = new Paragraph("制单：大厅管理员                 审核： 档案科张三             申请人：\n\n", fiveFont);
			 thrtionTitle.setLeading(10);
			 thrtionTitle.setAlignment(Element.ALIGN_LEFT);
			 document.add(thrtionTitle);

			 document.setMargins(0, 0, -5, 0);//单位磅 1英寸=72磅
			 document.newPage();
			 Image image = Image.getInstance("D:\\1702448735564.jpg");


//			 image.scaleToFit(PageSize.A4.getWidth()+100, PageSize.A4.getHeight());
			 image.scaleAbsolute(PageSize.A4.getWidth()+5, PageSize.A4.getHeight());
			 document.add(image);
			 // 关闭文档
			 document.close();
			 // 关闭书写器
			 writer.close();
		 }catch (Exception e){

		 }

		 return path;
	 }

	 @ApiOperation(value="上传文件", notes="上传文件")
	 @PostMapping(value = "/upload", consumes = "multipart/form-data")
	 public String uploadFile(@RequestParam("file") MultipartFile file) {
		 String ctxPath = uploadpath;
		 String ttxPath = thumbnail;
		 System.out.println("文件上传路径："+ctxPath);
		 String fileName = System.currentTimeMillis()+file.getOriginalFilename();
		 System.out.println("上传文件名："+fileName);
		 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		 File f=new File(ctxPath+df.format(new Date()));
		 if (!f.exists())
			 f.mkdirs();
		 File tf=new File(ttxPath+df.format(new Date()));
		 if (!tf.exists())
			 tf.mkdirs();
		 // 将文件名重新命名（因为可能会存在相同名字的文件）
		 String path = f.getAbsolutePath();
		 String  destFile =  path+"\\"+fileName;
		 File pfile = new File(path, fileName);
		 String url = Dpuburl;
		 url = url+df.format(new Date())+"/"+fileName;
		 pfile.getParentFile().mkdirs();
		 try {
			 file.transferTo(pfile);
		 } catch (IOException e) {
			 e.printStackTrace();
			 System.out.println("上传异常："+e.getMessage());
		 }

		 return url;
	 }
	public String convertBase64ToImage(String base64Str) {
		byte[] imageBytes = Base64.getDecoder().decode(base64Str);
		String url = Dpuburl;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
			BufferedImage image = ImageIO.read(bis);
			bis.close();
			String ctxPath = uploadpath;
			String ttxPath = thumbnail;
			String fileName = System.currentTimeMillis()+".png";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			File f=new File(ctxPath+df.format(new Date()));
			if (!f.exists())
				f.mkdirs();
			File tf=new File(ttxPath+df.format(new Date()));
			if (!tf.exists())
				tf.mkdirs();
			String path = f.getAbsolutePath();
			String  destFile =  path+"/"+fileName;
			url = url+df.format(new Date())+"/"+fileName;
			File outputFile = new File(destFile);
			ImageIO.write(image, "png", outputFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url;
	}
     public String base64File(String base64String){

		 base64String = base64String.replace("data:image/jpeg;base64,","");
		 base64String = base64String.replace("data:image/png;base64,","");
		 String url = Dpuburl;
		 try {
			 // 将base64字符串解码为字节数组
			 String ctxPath = uploadpath;
			 String ttxPath = thumbnail;
			 String fileName = System.currentTimeMillis()+".jpg";
			 byte[] imageData = Base64.getDecoder().decode(base64String);
			 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			 File f=new File(ctxPath+df.format(new Date()));
			 if (!f.exists())
				 f.mkdirs();
			 File tf=new File(ttxPath+df.format(new Date()));
			 if (!tf.exists())
				 tf.mkdirs();
			 String path = f.getAbsolutePath();
			 String  destFile =  path+"/"+fileName;
			 url = url+df.format(new Date())+"/"+fileName;
			 // 创建一个空的输出流
			 OutputStream outputStream = new FileOutputStream(destFile);

			 // 将字节数组写入输出流
			 outputStream.write(imageData);

			 // 关闭输出流
			 outputStream.close();
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
		 return url;
	 }

	 @ApiOperation(value="获取图片水印内容", notes="获取图片水印内容")
	 @GetMapping(value = "/watermarkinfo")
	 public Result<String> waterMarkInfo(HttpServletRequest request, HttpServletResponse response) {
		 String waterinfo = apiInfoService.watermarkinfo();
//		 System.out.println("水印内容：" + waterinfo);
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		 System.out.println("工号：" + loginUser.getUsername());
		 String ipAddress = request.getRemoteAddr();
//		 System.out.println("ip地址：" + ipAddress);
		 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		 String retStr = waterinfo.replace("user",loginUser.getUsername()).replace("ip",ipAddress).replace("date",df.format(new Date()));
//		 System.out.println("返回值：" + retStr);
		 return Result.ok(retStr);
	 }

	public String getSerialNumber(File drive) throws IOException {
		String os = System.getProperty("os.name").toLowerCase();
		if (os.contains("win")) {
			String driveLetter = drive.toString().substring(0, 1);
			Process process = Runtime.getRuntime().exec("cmd /c vol " + driveLetter);
			InputStream inputStream = process.getInputStream();
			Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
			if (scanner.hasNext()) {
				String volumeInfo = scanner.next();
				int serialNumberIndex = volumeInfo.indexOf("Serial Number");
				if (serialNumberIndex != -1) {
					return volumeInfo.substring(serialNumberIndex + 13).trim();
				}
			}
			scanner.close();
			inputStream.close();
		} else if (os.contains("nix") || os.contains("nux") || os.indexOf("mac") != -1) {
			Process process = Runtime.getRuntime().exec("udevadm info --query=all --name=" + drive);
			InputStream inputStream = process.getInputStream();
			Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
			if (scanner.hasNext()) {
				String udevInfo = scanner.next();
				int serialNumberIndex = udevInfo.indexOf("ID_SERIAL=");
				if (serialNumberIndex != -1) {
					int newlineIndex = udevInfo.indexOf("\n", serialNumberIndex);
					return udevInfo.substring(serialNumberIndex + 10, newlineIndex);
				}
			}
			scanner.close();
			inputStream.close();
		}
		return null;
	}

	private static String getWindowsSerialNumber() {
		String result = "";
		try {
			Process process = Runtime.getRuntime().exec(new String[] { "wmic", "diskdrive", "get", "serialnumber" });
			process.getOutputStream().close();
			Scanner scanner = new Scanner(process.getInputStream());
			scanner.next();
			result = scanner.next();
			scanner.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	private static String getUnixSerialNumber() {
		String result = "";
		try {
			Process process = Runtime.getRuntime().exec(new String[] { "udevadm", "info", "--query=all", "--name=/dev/sda" });
			process.getOutputStream().close();
			Scanner scanner = new Scanner(process.getInputStream());
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				if (line.contains("ID_SERIAL_SHORT")) {
					result = line.split("=")[1].trim();
					break;
				}
			}
			scanner.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	@ApiOperation(value="encode", notes="encode")
	@GetMapping(value = "/encode")
	public String encode(HttpServletRequest request, HttpServletResponse response) {
		String code =  request.getParameter("code");
		String os = System.getProperty("os.name").toLowerCase();
		if (os.contains("win")) {
			System.out.println("Serial Number: " + getWindowsSerialNumber());
		} else if (os.contains("nix") || os.contains("nux") || os.indexOf("mac") != -1) {
			System.out.println("Serial Number: " + getUnixSerialNumber());
		}
//		try {
//			File[] roots = File.listRoots();
//			for (File root : roots) {
//				String serialNumber = getSerialNumber(root);
//				System.out.println("Drive: " + root + ", Serial Number: " + serialNumber);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}

		try {
			String contentByAES = ZzSecurityHelper.encryptAES(code);
//			String contentByAES = ZzSecurityHelper.decryptAES(code);
			return contentByAES;
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

	}

	@ApiOperation(value="decode", notes="decode")
	@GetMapping(value = "/decode")
	public String decode(HttpServletRequest request, HttpServletResponse response) {
		String code =  "0dq4KNSQ1ODdD+DtCj6jxrO2TaITJrrTjU/0yMwys6DZRIR42+b4KVNwd9gjREBcN5hF4uWO1W+CgYc3Y/j0iBnF3DOs3nqUU6moA0E2IicIUu4ZbOkcWqnhEPKhZ0Ryks4piriGgvozZ14AXW7fjw==";//request.getParameter("code");

		try {
			String contentByAES = ZzSecurityHelper.decryptAES(code);
			return contentByAES;
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

	}

//	 @ApiOperation(value="上传文件", notes="上传文件")
//	 @RequestMapping(value = "/upload", method = {RequestMethod.PUT,RequestMethod.POST})
//	 public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req, Model model){
//
//	 	String ctxPath = uploadpath;
//	 	String fileName = System.currentTimeMillis()+file.getOriginalFilename();
//
//		 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//		 File f=new File(ctxPath+df.format(new Date()));
//		 if (!f.exists())
//			 f.mkdirs();
//		 // 将文件名重新命名（因为可能会存在相同名字的文件）
//		 String path = f.getAbsolutePath();
//		 String  destFile =  path+"\\"+fileName;
//		 File pfile = new File(path, fileName);
//		 String url = Dpuburl;
//		 url = url+df.format(new Date())+"/"+fileName;
//		 pfile.getParentFile().mkdirs();
//		 try {
//			 file.transferTo(pfile);
//		 } catch (IOException e) {
//			 e.printStackTrace();
//		 }
//		 return url;
//	 }


}
